<?php

namespace App\Library\FormFields;

use Kris\LaravelFormBuilder\Fields\FormField;
use Kris\LaravelFormBuilder\Form;

class ImageType extends FormField
{
    private $showPreview;
    private $uploadUrl;

    public function __construct(string $name, string $type, Form $parent, array $options = [])
    {
        parent::__construct($name, $type, $parent, $options);
        $this->parent->setFormOption('files', true);

        $this->showPreview = $options['show_preview'] ?? true;

        if (isset($options['upload_url']) && !is_null($options['upload_url'])) {
            $this->uploadUrl = $options['upload_url'];
        } elseif (isset($options['type']) && !is_null($options['type'])) {
            $this->uploadUrl = route('admin.upload_image', ['type' => $options['type']]);
        }
    }

    /**
     * @inheritDoc
     */
    protected function getTemplate()
    {
        return 'vendor.laravel-form-builder.image';
    }

    /**
     * @inheritDoc
     */
    public function render(array $options = [], $showLabel = true, $showField = true, $showError = true)
    {
        if (is_null($this->getValue())) {
            $this->setValue(\Form::old($this->name));
        }

        return parent::render($options, $showLabel, $showField, $showError);
    }

    public function getRenderData()
    {
        return [
            'showPreview' => $this->showPreview,
            'uploadUrl' => $this->uploadUrl,
        ];
    }
}
